package com.shanghaionstar.login.register;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.joinme.RegisterResponseEntity;
import com.onstar.cn.mag.joinme.RegisterToVisitorResponse;
import com.onstar.cn.weight.TimeButton;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.register.iview.IJoinMeView;
import com.shanghaionstar.login.register.presenter.JoinMePresenter;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.CommonInputLayout;
import com.shanghaionstar.weight.CommonProgressButton;
import com.shanghaionstar.weight.TopLayout;

/**
 * Created by 7828wc on 16/7/7.
 */
@ContentView(R.layout.joinme_finish_vin_register)
public class FinishVinRegisterActivity extends SwipeActivity implements IJoinMeView {
    private JoinMePresenter presenter;

    @FindViewById
    private RadioGroup rg_phone_email;
    @FindViewById
    private RadioButton rb_phone, rb_mail;
    @FindViewById
    private TextView tv_verify_name, tv_verify_type, tv_call_phone, tv_regcode_msg;
    @FindViewById
    private CommonInputLayout et_captcha, et_verify_code, et_user_pass;
    @FindViewById
    private TimeButton btn_get_code;
    @FindViewById
    private CommonProgressButton btn_submit;
    @FindViewById
    private Button btn_update_image;
    @FindViewById
    private RelativeLayout captcha_layout;
    @FindViewById
    private TopLayout top_layout;

    private String userPhone = "", userEmail = "", userNewEmail = "";
    private boolean isShowPassword = false;
    private boolean isGetCode = false;
    private boolean isSendEmail = false;
    private boolean isInfo3 = false;
    private String mFirstName = "";
    private String mLastName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new JoinMePresenter(getScheduler());
        presenter.setView(this);
        initView();
//        presenter.getCaptchaImage();

        btn_get_code.start(R.string.no_reveice_sms);


        setListener();
    }

    private void setListener() {
        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialogUtil.showAlertDialog(onActivity(), getString(R.string.dialog_warning), getString(R.string.comfirm_back),
                        R.string.btn_leave, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                finish();
                            }
                        }, true);
            }
        });

        et_user_pass.isShowPassword(isShowPassword);
        et_user_pass.setRightIconClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_user_pass.isShowPassword(!isShowPassword);
                isShowPassword = !isShowPassword;
            }
        });


        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!validateUserPass()) return;
                CommonUtil.hideKeyBoard(onActivity(), et_user_pass.getEditValue());
                if(captcha_layout.getVisibility() == View.VISIBLE) {
                    if (!isInfo3) {
                        presenter.registerOwnerByVinOrGovId(getIntent().getStringExtra("vinNumber"),
                                et_captcha.getText(), false, et_user_pass.getText(), et_verify_code.getText(),
                                rb_phone.isChecked() ? userPhone : "", rb_mail.isChecked() ? userEmail : "");
                    } else {
                        BusinessUtil.sendReportByClickType(FinishVinRegisterActivity.this, FunctionNameFindId.Register_Info3Subscriber.getStringValue());
                        presenter.registerOwnerByVinOrGovId(getIntent().getStringExtra("vinNumber"),
                                et_captcha.getText(), false, et_user_pass.getText(), et_verify_code.getText(),
                                rb_phone.isChecked() ? userPhone : "", rb_mail.isChecked() ? userEmail : "", mFirstName, mLastName);
                    }
                }else{
                    if (!isInfo3) {
                        presenter.registerOwnerByVinOrGovIdWithOutCatpcha(getIntent().getStringExtra("vinNumber"),
                                et_captcha.getText(), false, et_user_pass.getText(), et_verify_code.getText(),
                                rb_phone.isChecked() ? userPhone : "", rb_mail.isChecked() ? userEmail : "");
                    } else {
                        BusinessUtil.sendReportByClickType(FinishVinRegisterActivity.this, FunctionNameFindId.Register_Info3Subscriber.getStringValue());
                        presenter.registerOwnerByVinOrGovIdWithOutCatpcha(getIntent().getStringExtra("vinNumber"),
                                et_captcha.getText(), false, et_user_pass.getText(), et_verify_code.getText(),
                                rb_phone.isChecked() ? userPhone : "", rb_mail.isChecked() ? userEmail : "", mFirstName, mLastName);
                    }
                }
            }
        });
    }

    private boolean validateCode() {
        String password = et_verify_code.getText();
        et_verify_code.setHintText(R.string.phone_oremail_hint);
        if (CommonUtil.isNull(password)) {
            et_verify_code.setCheckHintText(R.string.input_user_info_not_null);
            return false;
        }
        et_user_pass.setCheckHintText("");
        return true;
    }

    private boolean validateUserPass() {
        String password = et_user_pass.getText();
        et_user_pass.setHintText(R.string.password_hint);
        if (CommonUtil.isNull(password)) {
//            et_user_pass.setHintText("");
            et_user_pass.setCheckHintText(R.string.input_user_info_not_null);
            return false;
        }
        if (!CommonUtil.checkInput(password)) {
//            et_user_pass.setHintText("");
            et_user_pass.setCheckHintText(R.string.SB021_MSG031);
            return false;
        }
        if (password.length() < 6 || password.length() > 20) {
//            et_user_pass.setHintText("");
            et_user_pass.setCheckHintText(R.string.userpass_error);
            return false;
        }
        if (!CommonUtil.passwordValidate(password)) {
//            et_user_pass.setHintText("");
            et_user_pass.setCheckHintText(R.string.userpass_error);
            return false;
        }
//        et_user_pass.setHintText(R.string.password_hint);
        et_user_pass.setCheckHintText("");
        return true;
    }


    private void initView() {
        StringBuffer sb = new StringBuffer();
        sb.append("<font color='#a6a6aa' size='32px'>" + getString(R.string.call_400));
        sb.append(DeviceUtil.isChineseLanguage() ? "</font><a href='tel:400-820-1188'><font color='#000000' size='34px'>400-820-1188</font></a>" : "<br/>please call </font><a href='tel:400-820-1188'>" +
                "<font color='#000000' size='34px'>400-820-1188</font></a>");
        tv_call_phone.setText(Html.fromHtml(sb.toString()));

        String email = getIntent().getStringExtra("userEmail");
        String phone = getIntent().getStringExtra("userPhone");
        if (!CommonUtil.isNull(email) && !CommonUtil.isNull(phone)) {
            //手机邮箱都存在，默认发送手机
            rb_phone.setVisibility(View.VISIBLE);
            rb_mail.setVisibility(View.VISIBLE);
            rb_phone.setChecked(true);

            userPhone = phone;
            userEmail = email;
            isSendEmail = false;

            tv_regcode_msg.setText(R.string.test_send_msg_phone);
            tv_verify_name.setText(R.string.login_tv_phone);
            tv_verify_type.setText(CommonUtil.replaceString(phone, false));
        } else if (!CommonUtil.isNull(email)) {
            //只存在邮箱，默认发送邮箱
            rb_phone.setVisibility(View.GONE);
            rb_mail.setVisibility(View.VISIBLE);

            userEmail = email;
            rb_mail.setChecked(true);
            isSendEmail = false;

            tv_regcode_msg.setText(R.string.test_send_msg_email);
            tv_verify_name.setText(R.string.login_mail);
            tv_verify_type.setText(CommonUtil.replaceString(email, true));
        } else if (!CommonUtil.isNull(phone)) {
            //只存在手机，默认发送手机
            rb_phone.setVisibility(View.VISIBLE);
            rb_mail.setVisibility(View.GONE);

            userPhone = phone;
            rb_phone.setChecked(true);
            isSendEmail = false;

            tv_regcode_msg.setText(R.string.test_send_msg_phone);
            tv_verify_name.setText(R.string.login_tv_phone);
            tv_verify_type.setText(CommonUtil.replaceString(phone, false));
        }
        isInfo3 = getIntent().getBooleanExtra("isInfo3",false);
        if(isInfo3){
            mFirstName = getIntent().getStringExtra("firstName");
            mLastName = getIntent().getStringExtra("lastName");
        }

    }

    @OnClick({R.id.btn_update_image, R.id.rb_mail, R.id.rb_phone, R.id.btn_get_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_update_image:
                presenter.getCaptchaImage();
                break;
            case R.id.rb_mail:
//                presenter.sendReport(FunctionNameFindId.ValidateMailAddress);
                userNewEmail = getIntent().getStringExtra("userNewEmail");
                userPhone = getIntent().getStringExtra("userPhone");
                rb_mail.setChecked(true);

                tv_regcode_msg.setText(R.string.test_send_msg_email);
                tv_verify_name.setText(R.string.login_mail);
                tv_verify_type.setText(CommonUtil.replaceString(userNewEmail, true));
                break;
            case R.id.rb_phone:
//                presenter.sendReport(FunctionNameFindId.ValidateMobile);
                userNewEmail = getIntent().getStringExtra("userNewEmail");
                userPhone = getIntent().getStringExtra("userPhone");
                rb_phone.setChecked(true);

                tv_regcode_msg.setText(R.string.test_send_msg_phone);
                tv_verify_name.setText(R.string.login_tv_phone);
                tv_verify_type.setText(CommonUtil.replaceString(userPhone, false));
                break;
            case R.id.btn_get_code:
                btn_get_code.setVisibility(View.GONE);
                isGetCode = true;
                setLoading(true);
                presenter.getCaptchaImage();
                presenter.getCode(getIntent().getStringExtra("vinNumber"),
                        false, "", "", rb_phone.isChecked() ? userPhone : "",
                        rb_mail.isChecked() ? userEmail : "");


//                presenter.registerOwnerByVinOrGovId(getIntent().getStringExtra("vinNumber"), et_captcha.getText(), false, "", "", rb_phone.isChecked() ? userPhone : "", rb_mail.isChecked() ? userEmail : "");
//                if (captcha_layout.getVisibility() != View.VISIBLE)
                    //首次输入注册失败则请求获取图形验证码
//                if(!isInfo3) {
//                    presenter.getCode(getIntent().getStringExtra("vinNumber"),
//                            false, "", "", rb_phone.isChecked() ? userPhone : "",
//                            rb_mail.isChecked() ? userEmail : "");
//                }else{
//                    presenter.getCode(getIntent().getStringExtra("vinNumber"),
//                            false, "", "", rb_phone.isChecked() ? userPhone : "",
//                            rb_mail.isChecked() ? userEmail : "");
//                }
                break;
            default:
                break;
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    public void showCaptchaImage(byte[] image) {
        showCaptchaView(true);
        et_captcha.showLoading(false);
        et_captcha.setCheckHintText(R.string.input_img_captcha_value);
        if (image != null) {
            et_captcha.setRightIcon(image);
        }
        btn_update_image.setVisibility(View.VISIBLE);
    }

    @Override
    public void showCaptchaView(boolean isShow) {
        captcha_layout.setVisibility(isShow ? View.VISIBLE : View.GONE);
        if (isShow) {
            btn_update_image.setVisibility(View.GONE);
            et_captcha.showLoading(true);
        }
    }

    @Override
    public void verifyInputResult(boolean result) {

    }

    @Override
    public void verifyCaptchaResult(String result) {
        setLoading(false);
        et_captcha.setCheckHintText(result);
    }

    @Override
    public void onResponseUpgradeSuccess(RegisterToVisitorResponse registerToVisitorResponse) {

    }

    @Override
    public void showInfoThreeView(boolean isShow) {

    }

    @Override
    public void showInfoLoading(boolean isLoading) {

    }

    @Override
    public void setLoading(boolean isLoading) {
        if (isGetCode) {
            btn_get_code.setVisibility(isLoading? View.GONE : View.VISIBLE);
//            btn_get_code.start(R.string.no_reveice_sms);
            verifyResult(et_verify_code, isLoading ? FinalConstants.Register.SHOW_LOADING : FinalConstants.Register.CHECK_CANCEl);
        } else {
            btn_submit.showLoading(isLoading);
        }
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(RegisterResponseEntity object) {
        if (isGetCode) {
            setLoading(false);
            isGetCode = false;
            btn_get_code.setVisibility(View.VISIBLE);
            btn_get_code.start(R.string.again_send);
        } else {
            PreferencesUtls.getInstance(this).putString(Constants.USER_NAME, !CommonUtil.isNull(userEmail) ? userEmail : userPhone);
            if (object != null) {
                PreferencesUtls.getInstance(this).putString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME, !CommonUtil.isNull(object.getEmailAddress()) ? userEmail : userPhone);
            } else {
                PreferencesUtls.getInstance(this).putString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME, !CommonUtil.isNull(userEmail) ? userEmail : userPhone);
            }
            AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), object.getBbwcMessage(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }
    }

    @Override
    public void verifyResult(View view, int errorResId) {
        if (view instanceof CommonInputLayout) {
            CommonInputLayout inputLayout = (CommonInputLayout) view;
            inputLayout.setEnabled(true);
            if (errorResId == FinalConstants.Register.NO_ERROR) {
                inputLayout.setCheckHintText(null);
            } else if (errorResId == FinalConstants.Register.CHECK_OK) {
                inputLayout.showLoading(false);
                inputLayout.setRightIcon(R.drawable.onstar_joinme_check_ok);
            } else if (errorResId == FinalConstants.Register.CHECK_CANCEl) {
                inputLayout.setRightIcon(-1);
                inputLayout.showLoading(false);
            } else if (errorResId == FinalConstants.Register.SHOW_LOADING) {
                inputLayout.showLoading(true);
            } else {
                inputLayout.setCheck(false);
                inputLayout.setCheckHintText(errorResId);
            }
        }
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        AlertDialogUtil.showAlertDialog(onActivity(), getString(R.string.dialog_warning), getString(R.string.comfirm_back),
                R.string.btn_leave, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        finish();
                    }
                }, true);
    }
}
